package com.szl.group.utils.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.springframework.stereotype.Component;


/**
 * @author: shenxiaolong
 * @date : 2020-07-22 11:42
 * @version: v1.0.0
 */
@Component
public class EasyExcelUtils extends EasyExcel {


    /**
     * @description: 分页查询、分批次写数据，避免导出大数据量时OOM
     * auto close resource
     * @param excelWriter
     * @param sheetName
     * @param totalCount 数据总数
     * @param pageQueryService
     */
    public void pageWrite(ExcelWriter excelWriter,
                                 String sheetName,
                                 long totalCount,
                                 MybatisPlusPageQueryService<?> pageQueryService) {

        // default export xlsx, page size 10000, sheet max row 1000000
        int pageSize = MybatisPlusPageQueryService.ExcelPageEnum.XLSX.getPageSize();
        int sheetMaxRow = MybatisPlusPageQueryService.ExcelPageEnum.XLSX.getSheetMaxRow();

        ExcelTypeEnum excelType = excelWriter.writeContext().writeWorkbookHolder().getExcelType();
        boolean isXls =  excelType != null && ExcelTypeEnum.XLS.getValue().equals(excelType.getValue());
        if (isXls) {
            pageSize = MybatisPlusPageQueryService.ExcelPageEnum.XLS.getPageSize();
            sheetMaxRow = MybatisPlusPageQueryService.ExcelPageEnum.XLS.getSheetMaxRow();//一个sheet页最大行数
        }

        // compute page count, sheet count
        long pageCount = (totalCount - 1) / pageSize + 1; //计算需要查询多少次
        long sheetCount = (totalCount - 1) / sheetMaxRow + 1;//计算需要几个sheet页
        int currentPage = 0;

        // page write data
        WriteSheet sheet = null;
        for (int i = 0; i < sheetCount; i++) {

            sheet = EasyExcel.writerSheet(i, sheetName + i).build();

            for (int j = 0; j < (sheetMaxRow / pageSize); j++) {//一个sheet页需要查询多少次

                // must use ++currentPage, mybatis-plus page query current page start 1
                excelWriter.write(pageQueryService.data(++currentPage, pageSize), sheet);

                if (currentPage >= pageCount) {
                    break;
                }
            }
        }

        // close source
        excelWriter.finish();
    }

}
